package beautiful.butterfly.server.httpserver.mvc.aop;

import beautiful.butterfly.server.httpserver.mvc.render.Render;

import java.util.ArrayList;
import java.util.List;

public abstract class InterceptorStack implements Interceptor {

    private List<Interceptor> interceptorList;
    private Interceptor[] interceptors;

    public InterceptorStack() {
        config();
        if (interceptorList == null) {
            throw new RuntimeException("请调用 addInterceptors(...)方法来配置InterceptorStack()方法");
        }
        /**
         * 需要将interceptorList转换为Interceptor[]形式,便于依次执行
         */
        interceptors = interceptorList.toArray(new Interceptor[interceptorList.size()]);
        interceptorList.clear();
        interceptorList = null;
    }

    /**
     * 把几个拦截器组合成一个拦截器栈<br/>
     * 调用{@link #addInterceptors(Interceptor...)}方法进行拦截器栈的添加<br/>
     */
    public abstract void config();

    /**
     * 把Interceptor数组转换成interceptorList.
     */
    protected final InterceptorStack addInterceptors(Interceptor... interceptors) {
        if (interceptors == null || interceptors.length == 0) {
            throw new IllegalArgumentException("添加的拦截器不能为空");
        }
        if (interceptorList == null) {
            interceptorList = new ArrayList<Interceptor>();
        }
        for (Interceptor interceptor : interceptors) {
            interceptorList.add(interceptor);
        }
        return this;
    }

    public Render doIt(InterceptorsAndActionExecute interceptorsAndActionExecute) {
        return new InterceptorsAndActionExecuteWrapper(interceptorsAndActionExecute, interceptors).invoke();
    }

}
